Graph = AceLibrary("AceAddon-2.0"):new(
	"AceConsole-2.0", "AceEvent-2.0", "AceDB-2.0", "AceDebug-2.0", "FuBarPlugin-2.0", "Parser-3.0", "Metrognome-2.0")
local dewdrop = AceLibrary("Dewdrop-2.0")
local tablet = AceLibrary("Tablet-2.0")

function Graph:OnInitialize()
	self:SetDebugging(true)
	self:RegisterMetro("Graph", self.UpdateTime, 1, self)
	self:RegisterParserEvent({
	    eventType = "Damage",
	    --sourceName = "player",
	}, "ParseHandler")
	
	self.damage = {}
	self.time = 0
	
	Graph:RegisterChatCommand({"/graph"}, self.options)
	self:Debug("/commands loaded")
end

function Graph:UpdateTime()
	self.time = self.time + 1
end

function Graph:ParseHandler(t)
	--assert(t.sourceName == "player")
	local source = t.sourceName
	if not self.damage[source] then
		self.damage[source] = {}
	end
	table.insert(self.damage[source], {amount = t.amount, time = self.time})
end

function Graph:OnEnable()
	self:RegisterEvent("PLAYER_REGEN_DISABLED")
	self:RegisterEvent("PLAYER_REGEN_ENABLED")
	
	self.graph = CreateFrame("Frame",nil,UIParent)
	self.graph:SetFrameStrata("BACKGROUND")
	self.graph:EnableMouse(true)
	self.graph:SetFrameStrata("MEDIUM")
	self.graph:SetMovable(true)
	self.graph:SetClampedToScreen(true)
	self.graph:SetWidth(200)  -- Set These to whatever height/width is needed 
	self.graph:SetHeight(200) -- for your Texture
	self.graph.t = self.graph:CreateTexture(nil,"ARTWORK")
	self.graph.t:SetTexture(0,0,0,1)
	self.graph.t:SetAllPoints(self.graph)
	--[[self.graph:SetBackdrop( { 
		bgFile = "Interface\\Tooltips\\UI-Tooltip-Background", 
		edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border", tile = true, tileSize = 16, edgeSize = 16, 
		insets = { left = 0, right = 0, top = 0, bottom = 0 }
    })
	self.graph:SetBackdropColor(0,0,0,1)]]--
	self.graph:SetPoint("CENTER",0,0)
	self.graph:SetScript("OnMouseDown",function()
        if ( arg1 == "LeftButton" ) then
			this:StartMoving()
		end
    end)
    self.graph:SetScript("OnMouseUp",function()
        if ( arg1 == "LeftButton" ) then
			this:StopMovingOrSizing()
		end
    end)
	self.graph:Hide()
end

function Graph:GraphIt()
	local dmg = {
		[0] = {},
	}
	local total = {
		[0] = 0,
	}
	local colors = {}
	for name in pairs(self.damage) do	--Go through every unit we have damage for
		colors[name] = math.random()
		dmg[0][name] = 1
		total[0] = total[0] + 1
		for i=1, self.time do			--For every second in combat
			if not dmg[i] then 
				dmg[i] = {} 
				total[i] = 0
			end
			dmg[i][name] = 0
			for _,v in ipairs(self.damage[name]) do	--Add any record at that time to the total for that time
				if (v.time == i) then
					dmg[i][name] = dmg[i][name] + v.amount
				end
			end
			dmg[i][name] = dmg[i][name] + dmg[i-1][name] --Add the previous time to this one
			total[i] = total[i] + dmg[i][name]			 --And update the total damage dealt up to this point
		end
	end
	
	local width = tonumber(format("%d", 200/(self.time+1)))
	if width < 1 then width = 1 end
	
	self.graph.tex = {}
	local count = 0
	for k in self:Sorted(dmg) do
		count = 0
		self:Debug(k)
		self.graph.tex[k] = {}
		self.graph.tex[k] = CreateFrame("Frame", nil, self.graph)
		self.graph.tex[k][0] = self.graph:CreateTexture(nil,"ARTWORK")
		self.graph.tex[k][0]:SetPoint("BOTTOMLEFT", self.graph, "BOTTOMLEFT", k*width, 0)
		self.graph.tex[k][0]:SetTexture(math.random(), math.random(), math.random())
		self.graph.tex[k][0]:SetHeight(1)
		self.graph.tex[k][0]:SetWidth(width)
		self:Debug(k, "Frame made")
		for x, v in self:Sorted(dmg[k]) do
			count = count + 1
			self:Debug(k, x, v, count) --k = time, x = unit, v = amount
			self.graph.tex[k][count] = self.graph:CreateTexture(nil,"ARTWORK")
			self.graph.tex[k][count]:SetTexture(colors[x],colors[x],colors[x])
			self.graph.tex[k][count]:SetPoint("BOTTOMLEFT", self.graph.tex[k][count-1], "TOPLEFT")
			self.graph.tex[k][count]:SetHeight((v/total[k])*200)
			self.graph.tex[k][count]:SetWidth(width)
			--self:Print(self.graph.tex[k][x]:SetScript("OnShow", function() self:Hide() end))
		end
	end
	self.graph:Show()
	self:Debug("Done")
end

function Graph:OnDisable()
	
end

function Graph:PLAYER_REGEN_ENABLED()
	self:StopMetro("Graph")
end

function Graph:PLAYER_REGEN_DISABLED()
	self.time = 0
	self.damage = {}
	self:StartMetro("Graph")
end

function Graph:Sorted(t, f)
	local a = {}
	for n in pairs(t) do table.insert(a, n) end
	table.sort(a, f)
	local i = 0      -- iterator variable
	local iter = function ()   -- iterator function
		i = i + 1
		if a[i] == nil then return nil
		else return a[i], t[a[i]]
		end
	end
	return iter
end

function Graph:Bug()
	for n, t in pairs(self.damage) do
		self:Print(n)
		for k, v in pairs(self.damage[n]) do
			self:Print(v.time, v.amount)
		end
	end
end
